import * as vscode from 'vscode';

import { compile } from 'json-schema-to-typescript';


export default function docType(context: vscode.ExtensionContext) {

  let a = vscode.commands.registerCommand('zd-vscode-tools.docType', () => {
    vscode.window.showInputBox(
      {
        password: false, // 输入内容是否是密码
        ignoreFocusOut: true, // 默认false，设置为true时鼠标点击别的地方输入框不会消失
        placeHolder: '输入要生成类型的接口？', // 在输入框内的提示信息
        prompt: '输入要生成类型的接口', // 在输入框下方的提示信息
      }).then(async function (msg) {

      const editor = vscode.window.activeTextEditor;

      if (editor) {
        // 获取当前编辑器的文档对象
        const document = editor.document;
        // 获取当前光标位置
        const position = editor.selection.active;

        let json = JSON.parse(
            msg?.replace(/"Null"/g, `"NullType"`)
              .replace(/#\/components\/schemas\//g, '#/') as string);

        const components:any = json['components'] || {
          ...json,
        };
        const keys = Object.keys(components);

        let insertCode = '';

        for (let key of keys) {
          console.log(key, components?.[key]);

          const properties = Object.keys(components?.[key]?.['properties']);

          for (let property of properties) {
            let ref:any = components[key]['properties'][property]['$ref']
              ? { '$ref': components[key]['properties'][property]['$ref'].replace('#/components/schemas/', '#/') }
              : {};

            if ([ '#/Null' ].indexOf(ref['$ref']) > -1) {
              ref = {
                $ref: ref['$ref'] + 'Type',
                refType: ref['$ref'] + 'Type',
              };
              components['NullType'] = {
                "type": "object",
                "description": "返回结果",
                "properties": {},
              };
            }

            if (components?.[key]?.['properties'][property]) {
              components[key]['properties'][property] = {
                ...components[key]['properties'][property],
                ...ref,
              };
            }
          }

          let schema:any = {
            "id": key,
            "title": key,
            "type": "object",
            "properties": components?.[key]?.['properties'],
            ...components,
          };
          let res;

          try {
            res = await compile(schema, key, {
              bannerComment: '',
              style: {

              },
            });
          } catch (err) {
            console.log(err);
          }
          insertCode += res;
        }

        insertCode = insertCode.replace(/.*\[k:.*string\]:.*unknown;/g, '')
          .replace(/(?<=\S*)DTO(?<=\s*)/g, '');
        const insertCodeArr = insertCode.split('export');

        insertCode = Array.from(new Set(insertCodeArr)).join('export');

        editor.edit((editBuilder) => {
          editBuilder.insert(position, insertCode);
        });
        // 保存文档
        document.save();
      }
    });
  });

  context.subscriptions.push(a);
}